﻿using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Net;
using System;
using System.IO;
using System.Web;

namespace sBlog.Net.Common
{
    public class ImageUtility
    {
        public static void FtpCreateFolder(string strFolder, string ftpUser, string ftpPassword)
        {
            try
            {
                FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(strFolder);
                ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
                ftp.Credentials = new NetworkCredential(ftpUser, ftpPassword);
                ftp.UsePassive = false;
                FtpWebResponse CreateForderResponse = (FtpWebResponse)ftp.GetResponse();
            }
            catch (Exception ex)
            {
                //Log("Error FtpCreateFolder: " + ex.Message + "---" + strFolder + "---" + ftpUser );
            }
        }

        public static void UpFileServer(string strUrl, Byte[] buffer)
        {
            try
            {
                string strUserNameFtp = System.Configuration.ConfigurationManager.AppSettings["ftpUserName"].ToString();
                string strPassFtp = System.Configuration.ConfigurationManager.AppSettings["ftpPassword"].ToString();

                FtpWebRequest requestObj = (FtpWebRequest)FtpWebRequest.Create(strUrl);
                requestObj.Method = WebRequestMethods.Ftp.UploadFile;
                requestObj.UseBinary = true;
                requestObj.KeepAlive = false;
                requestObj.Credentials = new NetworkCredential(strUserNameFtp, strPassFtp);
                Stream requestStream = requestObj.GetRequestStream();
                requestStream.Write(buffer, 0, buffer.Length);

                requestStream.Flush();
                requestStream.Close();
                requestObj = null;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static Bitmap cropImageRectangleCenter(Bitmap imgToResize, Rectangle cropArea)
        {
            System.Drawing.Image initImage = imgToResize;
            int templateWidth = cropArea.Width;
            int templateHeight = cropArea.Height;
            System.Drawing.Image returnImage;

            if (initImage.Width <= templateWidth && initImage.Height <= templateHeight)
            {
                returnImage = imgToResize;
            }
            else
            {
                double templateRate = double.Parse(templateWidth.ToString()) / templateHeight;
                double initRate = double.Parse(initImage.Width.ToString()) / initImage.Height;
                if (templateRate == initRate)
                {
                    System.Drawing.Image templateImage = new System.Drawing.Bitmap(templateWidth, templateHeight);
                    System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, templateWidth, templateHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);
                    returnImage = (Image)templateImage.Clone();
                    templateImage.Dispose();
                }
                else
                {
                    System.Drawing.Image pickedImage = null;
                    System.Drawing.Graphics pickedG = null;


                    Rectangle fromR = new Rectangle(0, 0, 0, 0);
                    Rectangle toR = new Rectangle(0, 0, 0, 0);


                    if (templateRate > initRate)
                    {

                        pickedImage = new System.Drawing.Bitmap(initImage.Width, int.Parse(Math.Floor(initImage.Width / templateRate).ToString()));
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);


                        fromR.X = 0;
                        fromR.Y = int.Parse(Math.Floor((initImage.Height - initImage.Width / templateRate) / 2).ToString());
                        fromR.Width = initImage.Width;
                        fromR.Height = int.Parse(Math.Floor(initImage.Width / templateRate).ToString());


                        toR.X = 0;
                        toR.Y = 0;
                        toR.Width = initImage.Width;
                        toR.Height = int.Parse(Math.Floor(initImage.Width / templateRate).ToString());
                    }

                    else
                    {
                        pickedImage = new System.Drawing.Bitmap(int.Parse(Math.Floor(initImage.Height * templateRate).ToString()), initImage.Height);
                        pickedG = System.Drawing.Graphics.FromImage(pickedImage);

                        fromR.X = int.Parse(Math.Floor((initImage.Width - initImage.Height * templateRate) / 2).ToString());
                        fromR.Y = 0;
                        fromR.Width = int.Parse(Math.Floor(initImage.Height * templateRate).ToString());
                        fromR.Height = initImage.Height;

                        toR.X = 0;
                        toR.Y = 0;
                        toR.Width = int.Parse(Math.Floor(initImage.Height * templateRate).ToString());
                        toR.Height = initImage.Height;
                    }


                    pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;


                    pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);


                    System.Drawing.Image templateImage = new System.Drawing.Bitmap(templateWidth, templateHeight);
                    System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, templateWidth, templateHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel);


                    templateG.Dispose();
                    returnImage = (Image)templateImage.Clone();
                    templateImage.Dispose();

                    pickedG.Dispose();
                    pickedImage.Dispose();
                }
            }

            initImage.Dispose();
            return new Bitmap(returnImage);
        }

        public static Byte[] SaveImage(Bitmap img, long quality)
        {
            EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);

            ImageCodecInfo jpegCodec = getEncoderInfo("image/jpeg");

            if (jpegCodec == null)
                return null;

            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;
            MemoryStream objStream = new MemoryStream();
            img.Save(objStream, jpegCodec, encoderParams);
            return objStream.ToArray();
        }

        private static ImageCodecInfo getEncoderInfo(string mimeType)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }

        public static Image ScaleBySize(Image imgPhoto, int sizeW, int sizeH)
        {
            int logoSize = sizeW;

            float sourceWidth = imgPhoto.Width;
            float sourceHeight = imgPhoto.Height;
            float destHeight = 0;
            float destWidth = 0;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            // Resize Image to have the height = logoSize/2 or width = logoSize.
            // Height is greater than width, set Height = logoSize and resize width accordingly
            if (sourceWidth > (2 * sourceHeight))
            {
                destWidth = sizeW;
                destHeight = sizeH;// (float)(sourceHeight * logoSize / sourceWidth);
            }
            else
            {
                int h = logoSize / 2;
                destHeight = sizeH;// h;
                destWidth = sizeW;// (float)(sourceWidth * h / sourceHeight);
            }
            // Width is greater than height, set Width = logoSize and resize height accordingly

            Bitmap bmPhoto = new Bitmap((int)destWidth, (int)destHeight,
                                        PixelFormat.Format32bppPArgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, (int)destWidth, (int)destHeight),
                new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();

            return bmPhoto;
        }

        public static bool UploadToFTP(string strFTPFilePath, byte[] fileContents, string strUserName, string strPassword)
        {
            try
            {
                //Create a FTP Request Object and Specfiy a Complete Path
                FtpWebRequest reqObj = (FtpWebRequest)WebRequest.Create(strFTPFilePath);

                //Call A FileUpload Method of FTP Request Object
                reqObj.Method = WebRequestMethods.Ftp.UploadFile;

                //If you want to access Resourse Protected,give UserName and PWD
                reqObj.Credentials = new NetworkCredential(strUserName, strPassword);

                // Copy the contents of the file to the byte array.
                //byte[] fileContents = File.ReadAllBytes(strLocalFilePath);
                reqObj.ContentLength = fileContents.Length;

                //Upload File to FTPServer
                Stream requestStream = reqObj.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();
                FtpWebResponse response = (FtpWebResponse)reqObj.GetResponse();
                response.Close();
            }

            catch (Exception Ex)
            {
                throw Ex;
            }
            return true;
        }

        public static bool UploadVideoToFTP(string strFTPFilePath, string strLocalFilePath, string strUserName, string strPassword)
        {
            try
            {
                //Create a FTP Request Object and Specfiy a Complete Path
                FtpWebRequest reqObj = (FtpWebRequest)WebRequest.Create(strFTPFilePath);

                //Call A FileUpload Method of FTP Request Object
                reqObj.Method = WebRequestMethods.Ftp.UploadFile;

                //If you want to access Resourse Protected,give UserName and PWD
                reqObj.Credentials = new NetworkCredential(strUserName, strPassword);

                // Copy the contents of the file to the byte array.
                byte[] fileContents = File.ReadAllBytes(strLocalFilePath);
                reqObj.ContentLength = fileContents.Length;

                //Upload File to FTPServer
                Stream requestStream = reqObj.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();
                FtpWebResponse response = (FtpWebResponse)reqObj.GetResponse();
                response.Close();
            }

            catch (Exception Ex)
            {
                throw Ex;
            }
            return true;
        }

        public static string GetFolderByDate(string strRoot)
        {
            if (strRoot.Substring(strRoot.Length - 1) != "/")
                strRoot += "/";
            return GetFullFolder(strRoot);
        }

        public static void UploadVideoClip(string strUrl, HttpPostedFileBase files, string strName, string userName, string pass)
        {
            try
            {
                Stream objStream = files.InputStream;
                Byte[] buffer = new Byte[files.ContentLength];
                objStream.Read(buffer, 0, buffer.Length);
                objStream.Close();
                objStream = null;

                FtpWebRequest requestObj = (FtpWebRequest)FtpWebRequest.Create(strUrl);
                requestObj.Method = WebRequestMethods.Ftp.UploadFile;

                requestObj.UseBinary = true;
                requestObj.Credentials = new NetworkCredential(userName, pass);
                requestObj.KeepAlive = false;

                Stream ReqStream = requestObj.GetRequestStream();
                ReqStream.Write(buffer, 0, buffer.Length);
                ReqStream.Flush();
                ReqStream.Close();
                requestObj = null;

                requestObj = (FtpWebRequest)FtpWebRequest.Create(strUrl);
                requestObj.Credentials = new NetworkCredential(userName, pass);

                requestObj.Method = WebRequestMethods.Ftp.Rename;
                requestObj.RenameTo = strName.Replace("xyz", "mp4");
                requestObj.GetResponse();
            }
            catch (Exception ex)
            {
                //Log("UploadVideoClip:" + ex.Message);
            }
        }

        public static string GetFullFolder(string strRoot)
        {
            string strDate = DateTime.Now.Year.ToString() + DateTime.Now.ToString("MM");
            strRoot += "/" + strDate;
            return strRoot;
        }
    }
}